<?php
// 确定配置键名，默认为'search-form'
$configKey = isset($configKey) ? $configKey : 'search-form';
// 搜索组件默认配置
$defaultConfig = [
    'section_id' => $configKey,
    'section_pretitle' => '搜索',
    'section_title' => '搜索文章、标签或作者',
    'section_subtitle' => '快速找到您需要的内容',
    'placeholder' => '搜索文章、标签或作者...',
    'search_icon' => 'fa-search',
    'close_icon' => 'fa-times',
    'submit_icon' => 'fa-arrow-right',
    'texts' => [
        'clear_history_text' => '清除历史记录',
        'no_results_text' => '没有找到相关结果',
        'search_history_label' => '搜索历史',
        'popular_searches_label' => '热门搜索',
        'author_articles_label' => '查看作者所有文章',
        'results_count_label' => '找到 {count} 个相关结果'
    ],
    'popular_searches' => [
        'JavaScript',
        'React',
        '前端开发',
        '性能优化'
    ],
    // 搜索历史存储键名
    'history_storage_key' => 'blog_search_history',
    // 最多显示的历史记录数量
    'max_history_items' => 5,
    // 搜索结果预览数量
    'preview_results_count' => 3,
    // 样式类名配置
    'classes' => [
        'container' => 'relative',
        'input' => 'w-full pl-10 pr-10 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all duration-300',
        'icon' => 'text-gray-400',
        'close_button' => 'absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 hidden',
        'submit_button' => 'absolute right-3 top-1/2 -translate-y-1/2 text-gray-600 hover:text-primary transition-colors',
        'results_container' => 'absolute left-0 right-0 mt-2 rounded-lg shadow-lg overflow-hidden z-50 hidden border border-gray-200',
        'results_header' => 'p-3 border-b border-gray-200',
        'results_count' => 'text-sm text-gray-500',
        'no_results' => 'p-6 text-center border-b border-gray-200',
        'no_results_icon' => 'fa fa-search text-gray-300 text-4xl mb-3',
        'no_results_text' => 'text-gray-500',
        'history_section' => 'p-4 border-b border-gray-200',
        'history_header' => 'flex justify-between items-center mb-3',
        'history_label' => 'font-medium text-gray-700',
        'clear_history' => 'text-sm text-gray-500 hover:text-red-500',
        'history_list' => 'space-y-2',
        'history_item' => 'w-full flex items-center text-left py-1 text-gray-600 hover:text-primary',
        'history_item_icon' => 'fa fa-history text-gray-400 mr-2',
        'popular_section' => 'p-4',
        'popular_label' => 'font-medium text-gray-700 mb-3',
        'popular_tags' => 'flex flex-wrap gap-2',
        'popular_item' => 'px-3 py-1 border border-gray-200 rounded-full text-sm text-gray-700 hover:border-primary hover:text-primary transition-colors',
        'results_list' => 'max-h-96 overflow-y-auto',
        'result_item' => 'flex p-4 hover:bg-gray-50 transition-colors',
        'result_image' => 'w-16 h-16 object-cover rounded-lg flex-shrink-0 mr-3',
        'result_content' => 'flex-grow min-w-0',
        'result_category' => 'text-xs px-2 py-0.5 bg-blue-100 text-blue-800 rounded-full mr-2',
        'result_title' => 'font-medium text-gray-900 mb-1 truncate',
        'result_excerpt' => 'text-sm text-gray-500 line-clamp-2',
        'result_tag_container' => 'w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center text-purple-600 flex-shrink-0 mr-3',
        'result_tag_icon' => 'fa fa-tag',
        'result_tag_name' => 'font-medium text-gray-900',
        'result_tag_count' => 'text-sm text-gray-500',
        'result_author_image' => 'w-10 h-10 rounded-full object-cover flex-shrink-0 mr-3',
        'result_author_name' => 'font-medium text-gray-900',
        'result_author_text' => 'text-sm text-gray-500'
    ]
];



// 合并配置（全局配置优先于默认配置）
$data = array_merge($defaultConfig, $pageConfig['components'][$configKey] ?? []);

// 示例搜索结果数据（实际应用中应从后端API获取）
$sampleResults = [
    [
        'type' => 'post',
        'id' => 1,
        'title' => '2023年前端开发趋势与最佳实践',
        'excerpt' => '探索2023年影响前端开发的关键技术趋势，包括框架选择、性能优化和用户体验设计的最佳实践...',
        'url' => '/blog/1',
        'category' => '网页开发',
        'image' => 'https://picsum.photos/seed/blog1/100/100'
    ],
    [
        'type' => 'post',
        'id' => 6,
        'title' => 'TypeScript高级类型技巧与实践',
        'excerpt' => '深入探讨TypeScript的高级类型特性，包括泛型、条件类型和映射类型在实际项目中的应用...',
        'url' => '/blog/6',
        'category' => '网页开发',
        'image' => 'https://picsum.photos/seed/blog6/100/100'
    ],
    [
        'type' => 'tag',
        'name' => 'JavaScript',
        'count' => 32,
        'url' => '/blog?tag=JavaScript'
    ],
    [
        'type' => 'author',
        'name' => '张明',
        'url' => '/author/zhangming',
        'avatar' => 'https://picsum.photos/seed/author1/100/100'
    ]
];
?>

<div class="<?php echo htmlspecialchars($data['classes']['container']); ?>" id="<?php echo htmlspecialchars($data['section_id']); ?>-component">
    <!-- 搜索输入框 -->
    <div class="relative">
        <input 
            type="text" 
            id="<?php echo htmlspecialchars($data['section_id']); ?>-input"
            placeholder="<?php echo htmlspecialchars($data['placeholder']); ?>"
            class="<?php echo htmlspecialchars($data['classes']['input']); ?>"
        >
        <i class="fa <?php echo htmlspecialchars($data['search_icon']); ?> absolute left-3 top-1/2 -translate-y-1/2 <?php echo htmlspecialchars($data['classes']['icon']); ?>"></i>
        <button id="<?php echo htmlspecialchars($data['section_id']); ?>-close" class="<?php echo htmlspecialchars($data['classes']['close_button']); ?>">
            <i class="fa <?php echo htmlspecialchars($data['close_icon']); ?>"></i>
        </button>
        <button id="<?php echo htmlspecialchars($data['section_id']); ?>-submit" class="<?php echo htmlspecialchars($data['classes']['submit_button']); ?>">
            <i class="fa <?php echo htmlspecialchars($data['submit_icon']); ?>"></i>
        </button>
    </div>

    <!-- 搜索结果下拉框 -->
    <div id="<?php echo htmlspecialchars($data['section_id']); ?>-results" class="<?php echo htmlspecialchars($data['classes']['results_container']); ?>">
        <!-- 搜索结果内容将通过JavaScript动态填充 -->
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 从PHP配置获取所有数据
    const config = <?php echo json_encode($data); ?>;
    const sampleResults = <?php echo json_encode($sampleResults); ?>;
    
    // 获取DOM元素
    const searchComponent = document.getElementById(`${config.section_id}-component`);
    const searchInput = document.getElementById(`${config.section_id}-input`);
    const searchClose = document.getElementById(`${config.section_id}-close`);
    const searchSubmit = document.getElementById(`${config.section_id}-submit`);
    const searchResults = document.getElementById(`${config.section_id}-results`);
    
    // 从本地存储获取搜索历史
    function getSearchHistory() {
        const history = localStorage.getItem(config.history_storage_key);
        return history ? JSON.parse(history) : [];
    }
    
    // 保存搜索历史到本地存储
    function saveSearchHistory(query) {
        if (!query.trim()) return;
        
        let history = getSearchHistory();
        // 移除已存在的相同查询
        history = history.filter(item => item.toLowerCase() !== query.toLowerCase());
        // 添加新查询到开头
        history.unshift(query);
        // 限制历史记录数量
        if (history.length > config.max_history_items) {
            history = history.slice(0, config.max_history_items);
        }
        
        localStorage.setItem(config.history_storage_key, JSON.stringify(history));
        return history;
    }
    
    // 清除搜索历史
    function clearSearchHistory() {
        localStorage.removeItem(config.history_storage_key);
        renderSearchResults();
    }
    
    // 渲染搜索结果
    function renderSearchResults(query = '') {
        // 清空结果容器
        searchResults.innerHTML = '';
        
        if (!query.trim()) {
            // 显示搜索历史和热门搜索
            const history = getSearchHistory();
            
            let content = '';
            
            // 搜索历史
            if (history.length > 0) {
                content += `
                <div class="${config.classes.history_section}">
                    <div class="${config.classes.history_header}">
                        <h3 class="${config.classes.history_label}">${config.texts.search_history_label}</h3>
                        <button id="clear-history" class="${config.classes.clear_history}">
                            ${config.texts.clear_history_text}
                        </button>
                    </div>
                    <ul class="${config.classes.history_list}">
                `;
                
                history.forEach(item => {
                    content += `
                    <li>
                        <button class="history-item ${config.classes.history_item}">
                            <i class="${config.classes.history_item_icon}"></i>
                            ${item}
                        </button>
                    </li>
                    `;
                });
                
                content += `</ul></div>`;
            }
            
            // 热门搜索
            if (config.popular_searches.length > 0) {
                content += `
                <div class="${config.classes.popular_section}">
                    <h3 class="${config.classes.popular_label}">${config.texts.popular_searches_label}</h3>
                    <div class="${config.classes.popular_tags}">
                `;
                
                config.popular_searches.forEach(item => {
                    content += `
                    <button class="popular-item ${config.classes.popular_item}">
                        ${item}
                    </button>
                    `;
                });
                
                content += `</div></div>`;
            }
            
            searchResults.innerHTML = content;
            
            // 添加事件监听器
            if (history.length > 0) {
                document.getElementById('clear-history').addEventListener('click', clearSearchHistory);
                
                document.querySelectorAll('.history-item').forEach(button => {
                    button.addEventListener('click', function() {
                        searchInput.value = this.textContent.trim();
                        performSearch(this.textContent.trim());
                    });
                });
            }
            
            document.querySelectorAll('.popular-item').forEach(button => {
                button.addEventListener('click', function() {
                    searchInput.value = this.textContent.trim();
                    performSearch(this.textContent.trim());
                });
            });
            
        } else {
            // 显示搜索结果（实际应用中应从API获取）
            const results = sampleResults;
            
            if (results.length === 0) {
                searchResults.innerHTML = `
                <div class="${config.classes.no_results}">
                    <i class="fa ${config.classes.no_results_icon}"></i>
                    <p class="${config.classes.no_results_text}">${config.texts.no_results_text}</p>
                </div>
                `;
                return;
            }
            
            // 替换结果计数中的占位符
            const resultsCountText = config.texts.results_count_label.replace('{count}', results.length);
            
            let content = `
            <div class="${config.classes.results_header}">
                <p class="${config.classes.results_count}">${resultsCountText}</p>
            </div>
            <ul class="${config.classes.results_list}">
            `;
            
            results.forEach(item => {
                if (item.type === 'post') {
                    content += `
                    <li>
                        <a href="${item.url}" class="${config.classes.result_item}">
                            <img src="${item.image}" alt="${item.title}" class="${config.classes.result_image}">
                            <div class="${config.classes.result_content}">
                                <div class="flex items-center mb-1">
                                    <span class="${config.classes.result_category}">${item.category}</span>
                                </div>
                                <h4 class="${config.classes.result_title}">${item.title}</h4>
                                <p class="${config.classes.result_excerpt}">${item.excerpt}</p>
                            </div>
                        </a>
                    </li>
                    `;
                } else if (item.type === 'tag') {
                    content += `
                    <li>
                        <a href="${item.url}" class="${config.classes.result_item}">
                            <div class="${config.classes.result_tag_container}">
                                <i class="${config.classes.result_tag_icon}"></i>
                            </div>
                            <div class="${config.classes.result_content}">
                                <h4 class="${config.classes.result_tag_name}">${item.name}</h4>
                                <p class="${config.classes.result_tag_count}">${item.count} 篇文章</p>
                            </div>
                        </a>
                    </li>
                    `;
                } else if (item.type === 'author') {
                    content += `
                    <li>
                        <a href="${item.url}" class="${config.classes.result_item}">
                            <img src="${item.avatar}" alt="${item.name}" class="${config.classes.result_author_image}">
                            <div class="${config.classes.result_content}">
                                <h4 class="${config.classes.result_author_name}">${item.name}</h4>
                                <p class="${config.classes.result_author_text}">${config.texts.author_articles_label}</p>
                            </div>
                        </a>
                    </li>
                    `;
                }
            });
            
            content += `</ul>`;
            searchResults.innerHTML = content;
        }
        
        // 显示结果框
        searchResults.classList.remove('hidden');
    }
    
    // 执行搜索
    function performSearch(query) {
        // 保存搜索历史
        saveSearchHistory(query);
        // 渲染搜索结果
        renderSearchResults(query);
    }
    
    // 搜索输入事件
    searchInput.addEventListener('input', function() {
        const query = this.value.trim();
        
        // 显示/隐藏清除按钮
        if (query) {
            searchClose.classList.remove('hidden');
            searchSubmit.classList.add('hidden');
        } else {
            searchClose.classList.add('hidden');
            searchSubmit.classList.remove('hidden');
        }
        
        // 渲染搜索结果
        renderSearchResults(query);
    });
    
    // 清除搜索输入
    searchClose.addEventListener('click', function() {
        searchInput.value = '';
        searchClose.classList.add('hidden');
        searchSubmit.classList.remove('hidden');
        renderSearchResults();
    });
    
    // 提交搜索
    searchSubmit.addEventListener('click', function() {
        const query = searchInput.value.trim();
        if (query) {
            // 实际应用中，这里应该提交表单或跳转到搜索结果页
            window.location.href = `/search?query=${encodeURIComponent(query)}`;
        }
    });
    
    // 回车键提交搜索
    searchInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            const query = this.value.trim();
            if (query) {
                window.location.href = `/search?query=${encodeURIComponent(query)}`;
            }
        }
    });
    
    // 点击外部关闭搜索结果
    document.addEventListener('click', function(e) {
        if (!searchComponent.contains(e.target)) {
            searchResults.classList.add('hidden');
        }
    });
    
    // 初始渲染搜索历史和热门搜索
    renderSearchResults();
    
    // 聚焦输入框时显示结果
    searchInput.addEventListener('focus', function() {
        searchResults.classList.remove('hidden');
    });
});
</script>
    